import useUrlState from '@ahooksjs/use-url-state';
import { getDetailByUserName, getObjectsByUsername } from "../api"
import { Button, Descriptions, Divider, message, Spin, Table } from "antd";
import type { DescriptionsItemType } from "antd/es/descriptions";
import { NavLink } from "react-router";
import { useAntdTable, useRequest } from "ahooks";
import { columns } from './statics';
import copy from 'copy-to-clipboard';
export default function TokenManagerDetail() {
  const [state] = useUrlState();

  const getDetail: () => Promise<DescriptionsItemType[]> = async () => {
    const { message: details } = await getDetailByUserName(state.userName)
    return [
      { label: '用户名', children: details?.userName, span: 1, key: 'userName' },
      { label: '真实姓名', children: details?.realName, span: 1, key: 'realName' },
      {
        label: 'token', children: <div style={{
          color: '#1890ff',
          cursor: 'pointer'
        }} onClick={() => {
          copy(details?.token);
          message.success('已复制到剪贴板');
        }} title={details?.token} className='multi-line-2'>{details?.token}</div>, span: 1, key: 'token'
      },
      { label: 'token生成时间', children: details?.tokenDate, span: 1, key: 'tokenDate' },
    ]
  }

  const getTableData = async () => {
    const { message: list } = await getObjectsByUsername(state.userName)
    return {
      list: list.sort((a, b) => a.module.length - b.module.length).sort((a, b) => a.event.length - b.event.length),
      total: list.length
    }
  }

  const { data: items, loading } = useRequest(getDetail, {
    ready: !!state?.userName,
  })

  const { tableProps } = useAntdTable(getTableData, {
    ready: !!state?.userName,
  });


  return <Spin spinning={loading}>
    <Descriptions
      title="详情"
      extra={<Button type="default"><NavLink to="/layout/token-manager">返回</NavLink></Button>}
      items={items}
      column={1}
      styles={{ label: { width: '120px' } }}
      colon={false}
    />
    <Divider />
    <Table columns={columns} rowKey="id" style={{ overflow: 'auto' }} {...tableProps} />
  </Spin>
}